<?php

/*
 * 爱康体检报告解析
 */

function aikangParseDan($filename) {
    $a = file($filename);
    $lines = array();
    foreach ($a as $line => $content) {
        //echo 'line '.($line + 1).':'.$content;
        $content = rtrim($content);
        //$content = iconv("GB2312", "UTF-8", $content);
        $content = mb_convert_encoding($content, 'UTF-8', 'GB2312,GBK,UTF-8');
//        $encode = mb_detect_encoding($content, array("ASCII", 'UTF-8', 'GB2312', "GBK"));
//        if ($encode == "EUC-CN") {
//            $content = iconv("GB2312", "UTF-8", $content);
//        }
        if (strpos($content, "版权所有") === false && strpos($content, "健康检查报告") === false) {
            $lines[] = $content;
        }
    }
//    echo "<pre>";
//    print_r($lines);die();
    // 1. get basic reportinfo
    //$reportinfo = array('realname' => '', 'gender' => '', 'examno' => '', 'examdate' => '');
    $reportinfo = array();
    $reportValidate = array('realname' => '', 'gender' => '', 'examno' => '', 'examdate' => '');
    foreach ($lines as $oneLine) {
        if (strpos($oneLine, "欢迎您的光临") !== false) {
            preg_match("/\[(.*)]/", $oneLine, $matches);
            if (empty($matches)) {
                return false;
            }
//                var_dump($matches);continue;
            $reportValidate["address"] = $matches[1];
        }
        if (strpos($oneLine, "用户姓名") !== false) {
            $item = explode("：", $oneLine);
            $reportinfo[0] = array(
                'itemName' => "姓名",
                'itemValue' => $item[1],
            );
            $reportValidate['realname'] = $item[1];
        }
        if (strpos($oneLine, "性别") !== false) {
            $item = explode("：", $oneLine);
            $reportinfo[1] = array(
                'itemName' => "性别",
                'itemValue' => $item[1],
            );
            $reportValidate["gender"] = $item[1];
        }
        if (strpos($oneLine, "体检日期") !== false) {
            $item = explode("：", $oneLine);
            $reportinfo[2] = array(
                'itemName' => "体检日期",
                'itemValue' => $item[1],
            );
            $reportValidate["examdate"] = $item[1];
        }
    }

    // var_dump($lines);exit();
    if (!isset($reportValidate["realname"]) || !isset($reportValidate["gender"])) {
        return array("error" => '非法体检报告');
    }
//       var_dump($reportinfo);	//获取到用户基本信息




    $itemsArray = array();

    $scopeMark = "~";
    $otherMark = " ";
    $lastScope = 0;
    $isScope = 0;


    $nowProgramName = "";
    $programArray = array();

    // 2. get iteminfos
    foreach ($lines as $key => $oneLine) {
        if (strpos($oneLine, "专家指导") !== false) {
            $isScope = 3;
            $prefix = "";
        } elseif (strpos($oneLine, "检查项目") !== false) {
            //    大项目名称
            $nowProgramName = $lastLine;
            if (strpos($oneLine, "参考") !== false) {
                $isScope = 1;
            } else {
                $isScope = 2;
            }
            $prefix = "";
            $lastScope = 0;
        } else {

            if ($isScope != 3 && strpos($oneLine, "初步意见") !== FALSE) {
                $prefix = "";
                continue;
            }

            if ($isScope != 3 && strpos($oneLine, "视力") !== FALSE && strpos($oneLine, " ") === FALSE) {
                $prefix = "";
                continue;
            }

            if ($isScope != 3 && $oneLine == "") {
                $prefix = "";
                $lastScope = 0;
                continue;
            }

            if ($isScope != 3 && strpos($oneLine, "检查项目") === false && strpos($oneLine, "检查项目") !== false) {
                $prefix = "";
                $lastLine = $oneLine;
                continue;
            }

            //***      echo $prefix . " -------------88888\n";
            if ($isScope == 1) {
                $prefix = $prefix . "|" . $oneLine;
                if (strpos($oneLine, $scopeMark) !== false) {

                    $itemsArray[] = $prefix;
                    $programArray[] = $nowProgramName;
                    $prefix = "";
                }
            } elseif ($isScope == 2) {

                $size = count($itemsArray);

                if (strpos($oneLine, $otherMark) !== false) {
                    $itemsArray[] = $oneLine;
                    $programArray[] = $nowProgramName;
                    $prefix = "";
                } else {
                    if ($lastScope == $isScope) {
                        if (!in_array(trim($oneLine), array('内科', '尿常规', '肝功能', '肾功能', '血脂', '血糖', '肿瘤标志物', '心电图', '超声检查', 'X线检查', '杂项', '外科', '眼科', '耳鼻咽喉科', '血常规'))) {
                            $itemsArray[$size - 1] = $itemsArray[$size - 1] . $oneLine;
                        }
                    }
                }
            } elseif ($isScope == 3) {
                $prefix = $prefix . $oneLine . "\n";
            }
        }

        $lastLine = $oneLine;
        $lastScope = $isScope;
    }

    foreach ($itemsArray as $key => &$value) {
        //$string = '|红细胞刚性指|数|4.79 2.29~6.72';
        preg_match_all("/([\x{4e00}-\x{9fa5}]{1,}[|]{1,}[\x{4e00}-\x{9fa5}]{1,}|-[\x{4e00}-\x{9fa5}]{1,})(.+)/iu", $value, $match);
        if (!empty($match[0]) && !empty($match[1]) && !empty($match[2])) {
            $value = $match[1][0] . " " . $match[2][0];
        }
        $value = str_replace("|", "", $value);
    }

    //*** //体检报告最后的总结

    /*
     * 把小项中的内容整理成固定格式，key分别为itemName,itemValue,issue,normal,unit,
     * 思路：
     * 1.用空格分割$itemsArray
     * 2.分割后的$itemsArray包括"~",则分配到normal（范围）中
     * 3.其它的按照：itemName,itemValue,issue,normal,unit进行分配
     *
     */
    //  var_dump($itemsArray);  //转化前小项所有内容
    $itemsArrayResult = array();

    foreach ($itemsArray as $key => $val) {
        $val = preg_split('/[\n\r\t\s]+/isU', $val);
        //若包含缩写，则把缩写合并到itemName中
        /*
          if(ctype_alpha(substr($val[1],0,1))){
          $val[0]=$val[0].$val[1];
          unset($val[1]);
          }
         * * */
        if (preg_match("/[A-Z]/isU", $val[1])) {
            $val[0] = $val[0] . " " . $val[1];
            unset($val[1]);
        }

        //重新定义索引
        $val = array_values($val);

        //把小项的value和指定的key值合并
        $keys_two = array("itemName", "itemValue");
        $keys_three = array("itemName", "itemValue", "normal");



        $keys_four = array("itemName", "itemValue", "normal", "unit");
        $keys_five = array("itemName", "itemValue", "issue", "normal", "unit");
        $tzzs_four = array("itemName", "itemValue", "issue", "normal");//体重指数
        //	var_dump($val);continue;
        if (count($val) === 2) {
            //		var_dump($val);continue;
            $val_combine = array_combine($keys_two, $val);
            $str = explode(" ", trim($val[0]));
            //		var_dump($str);continue;
            if (count($str) == 2) {
                $val = array_merge($str, array($val[1]));
                $val_combine = array_combine($keys_three, $val);
            }
        } elseif (count($val) === 3) {
            $val_combine = array_combine($keys_three, $val);
        } elseif (count($val) === 4) {
             if(!in_array("体重指数", $val)){
                $val_combine = array_combine($keys_four, $val);
             }else{
                 $val_combine = array_combine($tzzs_four, $val);
             }
        } elseif (count($val) === 5) {
            $val_combine = array_combine($keys_five, $val);
        } else {
            $val_combine = array_combine($keys_two, explode(" ", $val[0]));
        }
        array_push($itemsArrayResult, $val_combine);
    }
    
      //各个itemSet中的内容，即每一小项指标
    $uniqueProgramArray = array_unique($programArray);  //$uniqueProgramArray为删除大项中的重复项目
    //var_dump($programArray);//大项所有名称
    /*
     * 循环value值唯一的大项数组，组成含有parentName和itemSet的数组
     */

    $arrayParentName = array();  //删除重复项，含有parentName和itemSet的数组
    foreach ($uniqueProgramArray as $key => $val) {
        $item = array("parentName" => $val, "itemSet" => array());
        array_push($arrayParentName, $item);
    }

    /*     * 生成最终结果* */
    $arrayItemResult = array();  //保存最终结果的最外层数组
    array_push($arrayItemResult, array("parentName" => "basic", "itemSet" => $reportinfo)); //添加用户基本信息
    //向itemSet中插入体检指标
    foreach ($arrayParentName as $key => $val) {      //循环含有parentName和itemSet的数组
        foreach ($programArray as $k => $v) {  //循环大项所有名称，共93个
            if ($v == $val["parentName"]) {
                array_push($val["itemSet"], $itemsArrayResult[$k]);
            }
        }
        array_push($arrayItemResult, $val);
    }

    array_push($arrayItemResult, array("parentName" => "总汇", "itemSet" => array(array("itemName" => "总汇", "itemValue" => $prefix))));  //添加总结
    return json_encode(array("data" => $arrayItemResult, "reportinfo" => $reportinfo), JSON_UNESCAPED_UNICODE);
}
